<?php


namespace app\manage\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\common\model\StoreWifi;
use think\Db;
use app\common\model\Store as Store_Model;
use app\manage\validate\Store as Store_Validate;
use app\common\model\QueueRule as Queue_Model;
use app\common\model\StoreWifi as Wifi_Model;
use app\common\model\RechargeCommissionRange;

/**
 * 门店
 * Class Store
 * @package app\manage\admin
 */
class Store extends Admin
{

    //门店列表
    public function index(){
        // 读取数据
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder();
        // 数据列表
        $data_list = Store_Model::where($map)->order($order)->paginate()->each(function ($item){
            $sale = Db::name('qt_sale')->where(['id'=>$item['sale_id']])->value('name');
            $item['sale_name'] = $sale;
            //总房间数
            $roomCount = Db::name('qt_room')->where(['store_id'=>$item['id']])->count();
            $item['room_count'] = $roomCount;
            //总技师数
            $roomCount = Db::name('qt_users')->where(['store_id'=>$item['id'],'group'=>'1','status'=>'0'])->count();
            $item['engineer_count'] = $roomCount;
            //总楼面数
            $roomCount = Db::name('qt_users')->where(['store_id'=>$item['id'],'group'=>'2','status'=>'0'])->count();
            $item['user_count'] = $roomCount;

            //总项目数
            $roomCount = Db::name('qt_project')->where(['store_id'=>$item['id'],'status'=>'1'])->count();
            $item['project_count'] = $roomCount;
            return $item;
        });

        foreach ($data_list as $k=>$v)
        {
            $data_list[$k]['advance_down_block'] = $v['advance_down_block']?$v['advance_down_block'].'分钟':'';
            $data_list[$k]['back_engineer_block'] = $v['back_engineer_block']?$v['back_engineer_block'].'分钟':'';
            $data_list[$k]['change_engineer_block'] = $v['change_engineer_block']?$v['change_engineer_block'].'分钟':'';
            $data_list[$k]['sale_viper_rate'] = $v['sale_viper_rate']?$v['sale_viper_rate'].'%':'';
            $data_list[$k]['cancel_order_block'] = $v['cancel_order_block']?$v['cancel_order_block'].'分钟':'';
            $data_list[$k]['change_pay_type_block'] = $v['change_pay_type_block']?$v['change_pay_type_block'].'分钟':'';
        }
        // 分页数据
        $page = $data_list->render();

        $btn_add = [
            'title' => '新增门店',
            'icon' => '',
            'class' => 'btn btn-info',
            'href' => url('add'),
        ];

        $btn_edit = [
            'title' => '修改门店',
            'icon' => 'fa fa-fw fa-pencil ',
            'class' => 'btn btn-info btn-sm',
            'href' => url('edit',['id' => "__id__"]),
        ];

        $btn_rule = [
            'title' => '排钟规则',
            'icon' => 'fa fa-fw fa-asterisk',
            'class' => 'btn btn-info btn-sm',
            'href' => url('rule',['id' => "__id__"]),
        ];

        $btn_wifi = [
            'title' => '考勤规则',
            'icon' => 'fa fa-fw fa-wifi',
            'class' => 'btn btn-info btn-sm',
            'href' => url('wifi',['id' => "__id__"]),
        ];

        $btn_recharge_range = [
            'title' => '充值提成设置',
            'icon' => 'fa fa-fw fa-ship',
            'class' => 'btn btn-info btn-sm',
            'href' => url('addRechargeRate',['id' => "__id__"]),
        ];

        $btn_range_lists = [
            'title' => '充值提成区间列表',
            'icon' => 'fa fa-fw fa-list-alt',
            'class' => 'btn btn-info btn-sm',
            'href' => url('rangeLists',['id' => "__id__"]),
        ];
        $saleData = Db::name('qt_sale')->column('name','id');
        //设置页面
        return ZBuilder::make('table')
            ->addColumn('name', '名称', 'text')
            ->addColumn('phone', '电话', 'text')
            ->addColumn('start_time', '营业时间（开始）', 'text')
            ->addColumn('end_time', '营业时间（结束）', 'text')
            ->addColumn('room_count', '总房间数', 'text')
            ->addColumn('project_count', '总项目数', 'text')
            ->addColumn('engineer_count', '总技师数', 'text')
            ->addColumn('user_count', '总楼面数', 'text')
            ->addColumn('sale_name', '代理人', 'text')
            ->addColumn('expire_time', '过期时间', 'datetime','','Y-m-d')
            ->addColumn('status','状态','status','',['0'=>'冻结:danger','1'=>'正常:success','2'=>'审核中:info'])
            ->addColumn('right_button', '操作', 'btn')
            ->setTableName('qt_store')// 指定数据表名
            ->setSearchArea([
                ['text:2','name','门店名称','like'],
                ['text:2','phone','手机号','eq'],
                ['select:2','status','状态','eq','',['0'=>'冻结','1'=>'正常','2'=>'审核中'],'1'],
                ['select:2','sale_id','代理人','eq','',$saleData],
            ])
            ->setPrimaryKey('id')
            ->addTopButton('add', $btn_add)// 添加顶部按钮
            ->addRightButton('edit', $btn_edit)// 添加顶部按钮
            ->addTopButton('enable') // 添加顶部按钮
            ->addTopButton('disable') // 添加顶部按钮
            ->addTopButton('delete') // 添加顶部按钮
            ->setPageTitle('门店列表')
            ->setRowList($data_list)// 设置表格数据
            ->setPages($page)// 设置分页数据
            ->fetch();
    }

    /**
     * 添加门店
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {

        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            $validate = new Store_Validate();

            if ($validate->check($data))
                $this->error($validate->getError());

            if ($page = Store_Model::create($data)) {
                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
        } else {
            return ZBuilder::make('form')
                ->addFormItems([
                ['image', 'avatar', '头像'],
                ['text', 'mobile', '门店电话'],
                ['time', 'start_time', '门店营业开始时间'],
                ['time', 'end_time', '门店结束时间'],
                ['text', 'advance_down_block', '','','',['允许提前下钟','分钟/0标示不允许提前下钟']],
                ['text', 'back_engineer_block', '','','',['退技师设置','/分钟可退']],
                ['text', 'change_engineer_block', '','','',['换技师设置','/分钟可换']],
                    ['radio', 'receiver_order_commission_type', '下单提成模式','',[1=>'按下单人项目不管技师做什么项目',2=>'按技师上钟项目不管下单人下什么项目',3=>'下单人下单项目和技师上钟项目必须相同才有提成']],
                    ['text', 'sale_viper_rate', '','','',['售卡提成','%设置之后充的卡才生效']],
                ['radio', 'type', '门店模式','',[1=>'普通模式',2=>'手牌模式']],
                ['radio', 'viper_pay_verify_type', '会员付款验证方式','',[1=>'仅验证码',2=>'仅密码',3=>'验证码+密码',4=>'验证码+自设密码']],
                ['text', 'cancel_order_block', '','','',['允许撤销多少小时内的订单','']],
                ['text', 'change_pay_type_block', '','','',['结账后','小时内的单允许更改付款方式']],
                ['text', 'engineer_down_notify_block', '','','',['技师下钟前','分钟发送提醒通知']],
                ['text', 'popup_disappear_block', '','','',['首页消息弹窗','s后自动消失']],
                ['radio', 'floor_commission_type', '楼面提成设置','',[1=>'按下单人',2=>'按开房人']],
                ['radio', 'is_more_recharge', '开启多人充值提成模：','',[1=>'是',0=>'否']],
                ['radio', 'is_print_viper_mobile', '打印会员手机号','',[1=>'是',0=>'否']],
                ['radio', 'is_viper_passwd_input', '会员默认密码不用手动输入','',[1=>'是',0=>'否']],
                ['radio', 'is_print_zero_order', '金额为0的订单不打印','',[1=>'是',0=>'否']],
                ['radio', 'is_auto_dirty_room', '自动脏房','',[1=>'是',0=>'否']],
                ['radio', 'is_hand_card_settle', '发手牌模式房间结账','',[1=>'是',0=>'否']],
                ['radio', 'is_delay_add_block', '超时自动加钟','',[1=>'是',0=>'否']],
                ['radio', 'is_main_act', '主项是否动牌','',[1=>'是',0=>'否']],
                ['radio', 'is_second_act', '副项是否动牌','',[1=>'是',0=>'否']],
                ['radio', 'is_mp_show', '公众号显示技术','',[1=>'是',0=>'否']],
                ['radio', 'is_auto_print', '手机端自动打印','',[1=>'是',0=>'否']],
                ['radio', 'is_auto_cloud_print', '自动云打印','',[1=>'是',0=>'否']],
                ['radio', 'is_auto_queue', '自动排钟','',[1=>'是',0=>'否']],
                ['radio', 'is_clean_room_check', '净房检查','',[1=>'是',0=>'否']],
                ['radio', 'is_second_queue_add_block', '副项排钟计入点排数','',[1=>'是',0=>'否']],
                ['radio', 'is_user_scan', '客人扫码点技师','',[1=>'是',0=>'否']],
                ['radio', 'is_viper_message', '是否默认会员短信接收','',[1=>'是',0=>'否']],
                ['radio', 'is_viper_money_show', '会员余额短信合计显示','',[1=>'是',0=>'否']],
                ['radio', 'is_engineer_show_amount', '技师app显示业绩','',[1=>'是',0=>'否']],
                ['radio', 'is_later_card', '迟到打卡','',[1=>'是',0=>'否']],
                ['radio', 'is_leave_early_card', '早退打卡','',[1=>'是',0=>'否']]
                ])
                ->setPageTitle('添加门店')
                ->fetch();
        }
    }

    /**
     * 编辑门店
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = null)
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            // 验证
            $validate = new Store_Validate();

            if ($validate->check($data))

                $this->error($validate->getError());

            if (Store_Model::where('id',$id)->update($data)) {
                $this->success('编辑成功', 'index',['_close_pop' => 1,'_parent_reload' => 1]);
            } else {
                $this->error('编辑失败');
            }
        } else {
            $info = Store_Model::get($id);

            return ZBuilder::make('form')
                ->addFormItems([
                    ['image', 'avatar', '头像'],
                    ['text', 'mobile', '门店电话'],
                    ['time', 'start_time', '门店营业开始时间'],
                    ['time', 'end_time', '门店结束时间'],
                    ['text', 'advance_down_block', '','','',['允许提前下钟','分钟/0标示不允许提前下钟']],
                    ['text', 'back_engineer_block', '','','',['退技师设置','/分钟可退']],
                    ['text', 'change_engineer_block', '','','',['换技师设置','/分钟可换']],
                    ['radio', 'receiver_order_commission_type', '下单提成模式','',[1=>'按下单人项目不管技师做什么项目',2=>'按技师上钟项目不管下单人下什么项目',3=>'下单人下单项目和技师上钟项目必须相同才有提成']],
                    ['text', 'sale_viper_rate', '','','',['售卡提成','%设置之后充的卡才生效']],
                    ['radio', 'type', '门店模式','',[1=>'普通模式',2=>'']],
                    ['radio', 'viper_pay_verify_type', '会员付款验证方式','',[1=>'仅验证码',2=>'仅密码',3=>'验证码+密码',4=>'验证码+自设密码']],
                    ['text', 'cancel_order_block', '','','',['允许撤销多少小时内的订单','']],
                    ['text', 'change_pay_type_block', '','','',['结账后','小时内的单允许更改付款方式']],
                    ['text', 'engineer_down_notify_block', '','','',['技师下钟前','分钟发送提醒通知']],
                    ['text', 'popup_disappear_block', '','','',['首页消息弹窗','s后自动消失']],
                    ['radio', 'floor_commission_type', '楼面提成设置','',[1=>'按下单人',2=>'按开房人']],
                    ['radio', 'is_more_recharge', '开启多人充值提成模：','',[1=>'是',0=>'否']],
                    ['radio', 'is_print_viper_mobile', '打印会员手机号','',[1=>'是',0=>'否']],
                    ['radio', 'is_viper_passwd_input', '会员默认密码不用手动输入','',[1=>'是',0=>'否']],
                    ['radio', 'is_print_zero_order', '金额为0的订单不打印','',[1=>'是',0=>'否']],
                    ['radio', 'is_auto_dirty_room', '自动脏房','',[1=>'是',0=>'否']],
                    ['radio', 'is_hand_card_settle', '发手牌模式房间结账','',[1=>'是',0=>'否']],
                    ['radio', 'is_delay_add_block', '超时自动加钟','',[1=>'是',0=>'否']],
                    ['radio', 'is_main_act', '主项是否动牌','',[1=>'是',0=>'否']],
                    ['radio', 'is_second_act', '副项是否动牌','',[1=>'是',0=>'否']],
                    ['radio', 'is_mp_show', '公众号显示技术','',[1=>'是',0=>'否']],
                    ['radio', 'is_auto_print', '手机端自动打印','',[1=>'是',0=>'否']],
                    ['radio', 'is_auto_cloud_print', '自动云打印','',[1=>'是',0=>'否']],
                    ['radio', 'is_auto_queue', '自动排钟','',[1=>'是',0=>'否']],
                    ['radio', 'is_clean_room_check', '净房检查','',[1=>'是',0=>'否']],
                    ['radio', 'is_second_queue_add_block', '副项排钟计入点排数','',[1=>'是',0=>'否']],
                    ['radio', 'is_user_scan', '客人扫码点技师','',[1=>'是',0=>'否']],
                    ['radio', 'is_viper_message', '是否默认会员短信接收','',[1=>'是',0=>'否']],
                    ['radio', 'is_viper_money_show', '会员余额短信合计显示','',[1=>'是',0=>'否']],
                    ['radio', 'is_engineer_show_amount', '技师app显示业绩','',[1=>'是',0=>'否']],
                    ['radio', 'is_later_card', '迟到打卡','',[1=>'是',0=>'否']],
                    ['radio', 'is_leave_early_card', '早退打卡','',[1=>'是',0=>'否']]
                ])
                ->setFormData($info)
                ->setPageTitle('编辑们门店')
                ->fetch();
        }
    }

    /**
     * 排钟规则
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function rule($id=null)
    {
        $info = Queue_Model::get(['store_id'=>$id]);

        if ($this->request->isPost())
        {
            $data = $this->request->post();

            $result = empty($info)?Queue_Model::create($data):Queue_Model::where('store_id',$data['store_id'])->update($data);

            if ($result)
            {
                $this->success('操作成功','index',['_close_pop' => 1,'_parent_reload' => 1]);
            }else{
                $this->error('操作失败');
            }
        }else{

            return ZBuilder::make('form')
                ->addFormItems([
                    ['radio', 'type', '规则类型','',['1'=>'大轮排','2'=>'上钟点排数']],
                    ['radio', 'is_down_act', '下钟动牌','',[1=>'是',0=>'否']],
                    ['radio', 'is_working_engineer_first', '是否优先排当班技师','',[1=>'是',0=>'否',]],
                    ['radio', 'is_working_dot_act', '工作时间点钟是否动牌','',[1=>'是',0=>'否',]],
                    ['radio', 'is_overtime_dot_act', '加班时间点钟是否动牌','',[1=>'是',0=>'否',]],
                    ['radio', 'is_overtime_auto_queue', '加班是否自动排钟','',[1=>'是',0=>'否']],
                    ['radio', 'rule', '排钟规则','',[1=>'不处理',2=>'合并班次',3=>'打卡班次',4=>'按照主项轮钟排序']],
                    ['radio', 'is_overtime_act_queue', '加班是否动牌','',[1=>'是',0=>'否']],
                    ['radio', 'second_act_type', '副项排钟','',[1=>'动排',2=>'不动排',3=>'手动牌']],
                ])
                ->addHidden('store_id',$id)
                ->setFormData($info)
                ->setPageTitle('查看排钟规则')
                ->fetch();
        }


    }

    /**
     * 考勤Wi-Fi
     * @param $id
     * @return mixed
     * @throws \think\Exception
     */
    public function wifi($id)
    {
        $list = Wifi_Model::where(['store_id'=>$id])->select();

        $btn_remove = [
            'title' => '删除wifi',
            'icon' => 'ffa fa-fw fa fa-fw fa-trash',
            'class' => 'btn btn-info btn-sm',
            'href' => url('removeWifi',['id' => "__id__"]),
        ];

        //设置页面
        return ZBuilder::make('table')
            ->addColumn('id', 'ID', 'text')
            ->addColumn('wifi', 'wifi名称', 'text')
            ->addColumn('mac', 'MAC地址', 'text')
            ->addColumn('right_button','操作','btn')
            ->addRightButton('remove',$btn_remove)
            ->setPageTitle('考勤规则')
            ->setRowList($list)// 设置表格数据
            ->fetch();
    }

    /**
     * 删除考勤wifi
     * @param null $id
     */
    public function removeWifi($id=null)
    {
        if (!$id)
            $this->error('删除wifi错误');

        $result = StoreWifi::destroy(['id'=>$id]);

        if ($result)
            $this->success('删除成功');
    }

    /**
     * 添加实际充值区间
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function addRechargeRate($id=null)
    {
        if ($this->request->isPost())
        {
            $data = $this->request->post();

            $result = RechargeCommissionRange::create($data);

            if ($result)
            {
                $this->success('添加成功','index');
            }else{
                $this->error('添加错误');
            }

        }else{
            return ZBuilder::make('form')
                ->addFormItems([
                    ['text', 'start', '充值区间开始'],
                    ['text', 'end', '充值区间结束'],
                    ['text', 'rate', '提成比例'],
                ])
                ->addHidden('store_id',$id)
                ->setPageTitle('添加实际充值区间')
                ->fetch();

        }
    }

    /**
     * 充值区间列表
     * @param $id
     * @return mixed
     * @throws \think\Exception
     */
    public function rangeLists($id)
    {
        $list = RechargeCommissionRange::where(['store_id'=>$id])->select();

        foreach ($list as $k=>$v)
        {
            $list[$k]['range'] = $v['start']&&$v['end']?$v['start'].'-'.$v['end']:'';
        }

        $btn_remove = [
            'title' => '删除',
            'icon' => 'ffa fa-fw fa fa-fw fa-trash',
            'class' => 'btn btn-info btn-sm',
            'href' => url('removeRange',['id' => "__id__"]),
        ];

        //设置页面
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->addColumn('id', 'ID', 'text')
            ->addColumn('range', '实际充值提成区间', 'text')
            ->addColumn('rate', '提成', 'text')
            ->addColumn('right_button','操作','btn')
            ->addRightButton('rrange',$btn_remove)
            ->setPageTitle('充值区间列表')
            ->setRowList($list)// 设置表格数据
            ->fetch();
    }

    /**
     * 移除充值区间
     * @param null $id
     */
    public function removeRange($id=null)
    {
        $info = RechargeCommissionRange::get($id);

        if (!$info)
            $this->error('记录不存在');

        $result = RechargeCommissionRange::destroy($id);

        $result?$this->success('删除成功','index'):$this->error('删除错误');
    }

}